package com.eascs.o2o.message.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.o2o.common.vo.ModelResult;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;  
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class HttpUtil {
	private static  Logger log = LoggerFactory.getLogger(new HttpUtil().getClass());

	public static String sendGet(String url,Map<String,String> param) {
    	if (StringUtils.isBlank(url) || param==null) {
			return null;
		}
    	StringBuffer sb=new StringBuffer(url);
    	int count=0;
    	for (String key : param.keySet()) {
    		if (count == 0) {
    			sb.append("?");
			}else{
				sb.append("&");
			}
    		String value=param.get(key);
    		sb.append(key+"="+value);
    		++count;
		}
    	return sendGet(sb.toString());
    }
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url) {
		log.info("----HttpUtil sendGet start,url:" + url);
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 设置连接超时和读取超时
			connection.setConnectTimeout(30 * 1000);
			connection.setReadTimeout(60 * 1000);
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			// Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			log.info("--HttpUtil sendGet error(catch) -->" + e.getMessage());
			result = "-99";
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {
				log.info("--HttpUtil sendGet error(finally) -->" + e.getMessage());
			}
		}
		log.info("----HttpUtil sendGet end");
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		log.info("----HttpUtil sendPost start,url:" + url + ",param:" + param);
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置连接超时和读取超时
			connection.setConnectTimeout(30 * 1000);
			connection.setReadTimeout(60 * 1000);
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			connection.setDoOutput(true);
			connection.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(connection.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			log.info("--HttpUtil sendPost error(catch) -->" + e.getMessage());
			result = "-99";
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				log.info("--HttpUtil sendPost error(finally) -->" + e.getMessage());
			}
		}
		log.info("----HttpUtil sendPost end");
		return result;
	}

	public static ModelResult<Boolean> convertXml(String xml) {
		log.info("----HttpUtil convertXml start,xml:" + xml);
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if (StringUtils.isBlank(xml)) {
			modelResult.withError("send message fail", "参数不能为空 ");
			log.info("--HttpUtil convertXml param null");
			return modelResult;
		}
		Document doc = null;
		try {
			// 下面的是通过解析xml字符串的
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			Element errorEl = rootElt.element("error");
			String errorText = errorEl.getText();
			if (errorText.trim().equals("0")) {
				log.info("--send message successful(errorState: " + errorText + ")");
				return modelResult.withModel(true);
			}
			Element messageEl = rootElt.element("message");
			String messageText = messageEl.getText();
			log.info("--send message fail(errorState: " + errorText + ",message:" + messageText + ")");
			modelResult.withError("send message fail", errorText+" "+messageText);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("----HttpUtil convertXml end");
		return modelResult;
	}

	public static void main(String[] args) {
		// String result="<?xml version='1.0'
		// encoding='UTF-8'?><response><error>0</error><message></message></response>";
		// convertXml(result);

		// 发送 GET 请求
		// String s =
		//HttpUtil.sendGet("http://hprpt2.eucp.b2m.cn:8080/sdkproxy/sendsms.action?cdkey=0SDK-EBB-6699-RDYOT&password=685363&phone=15919498342&message=【怡亚通】金融平台验证码{0}");
		//System.out.println("result=" + s);

		// 发送 POST 请求
		// String sr =
		// HttpUtil.sendPost("http://100.100.11.93:8088/sdkproxy/getmo.action",
		// "cdkey=0MTN-EMY-6688-JBQLL&password=555555");
		// System.out.println("result=" + sr);
		// System.out.println(ResultCode.cmpp20_connection_1.getCode());
	}
}
